package meta.api.web.operation.business;

import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import meta.api.web.operation.businessinfo.ValueInfo;
import meta.api.web.operation.dao.OpnMngDao;
import meta.common.util.JsonUtil;
import meta.common.util.ListUtil;

@Component
public class OpnMngService {

    @Autowired
    private OpnMngDao opnMngDao;

    public int getValueTotal(String type, String queryForKey) {
        return opnMngDao.getValueTotal(type, queryForKey);
    }

    public List<Object> getValueList(String type, String queryForKey, Integer current, Integer pageSize) {
        List<Object> result = new ArrayList<Object>();
        List<String> valueList =  opnMngDao.getValueList(type, queryForKey, current, pageSize);
        if (ListUtil.isNotEmptyList(valueList)) {
            for (String value : valueList) {
                result.add(JsonUtil.toObj(value, Object.class));
            }
        }
        return result;
    }

    public void saveValue(ValueInfo value) {
        @SuppressWarnings("unchecked")
        LinkedHashMap<String, ?> valueMap = (LinkedHashMap<String, ?>) value.getValue();
        String valueJsonStr = JsonUtil.toJsonStr(valueMap);

        // 检证值是否存在
        boolean exist = opnMngDao.checkExistValue(value.getType(), value.getKey());

        if (!exist) {
            // 新增值
            opnMngDao.insertValue(value.getType(), value.getKey(), valueJsonStr);
        } else {
            // 更新值
            opnMngDao.updateValue(value.getType(), value.getKey(), valueJsonStr);
        }
    }

    public void deleteValue(ValueInfo value) {
        opnMngDao.deleteValue(value.getType(), value.getKey());
    }
}
